package com.yzt.message.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.yzt.redpack.dialog.GameRedPkgDialog;
import com.yzt.redpack.dialog.RedPkgDialog;
import com.yzt.zhuju.arouter.RouterMessage;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.constants.IntentConstant;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.dialog.ChatRoomGiftDialog;
import com.yzt.zhuju.event.im.RongYunMessageUnreadStatusEvent;
import com.yzt.zhuju.event.message.QuitGroupEvent;
import com.yzt.zhuju.gift.GiftBatterManager;
import com.yzt.zhuju.gift.GiftManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.chatroom.GiftIconEvent;
import com.yzt.zhuju.network.entity.gift.GiftOpenInfo;
import com.yzt.zhuju.network.entity.user.GroupProfileBase;
import com.yzt.zhuju.network.entity.user.GroupProfileList;
import com.yzt.zhuju.network.entity.user.PersonalDetailBasic;
import com.yzt.zhuju.permission.PermissionsUtils;
import com.yzt.zhuju.utils.AndroidBug5497Workaround;
import com.yzt.zhuju.utils.DiceUtil;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.p_base.utils.KeyboardUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.message.ConversationCache;
import com.yzt.message.MySendImageManager;
import com.yzt.message.R;
import com.yzt.message.fragment.MessageFragment;

import com.yzt.message.observer.ChatInputLoadManager;
import com.yzt.message.observer.RySendImageManager;

import com.yzt.message.widget.chatinput.listener.OnMenuClickListener;
import com.yzt.message.widget.chatinput.listener.RecordVoiceListener;
import com.yzt.message.widget.chatinput.model.FileItem;
import com.yzt.message.widget.chatinput.widget.ChatInputView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import io.rong.imkit.RongIM;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.HQVoiceMessage;

@SuppressLint({"SetTextI18n", "MissingSuperCall", "DefaultLocale"})
@Route(path = RouterMessage.ACTIVITY_CONVERSITY)
public class ConversationActivity extends BaseActivity implements RySendImageManager.RySendImageObservable,
        ChatInputLoadManager.ChatInputLoadObservable, View.OnClickListener {

    @Autowired
    String mHisNickname;

    @Autowired
    String mHisAccid;

    @Autowired
    int displayMode;

    @Autowired
    boolean isGroup;

    public ConversationActivity instance;

    String hisAccId;

    String hisNickname;

    private MessageFragment mConversationFragment;

    private Uri uri;

    private Conversation.ConversationType mConversationType;

    private PersonalDetailBasic mUserInfo;

    private GroupProfileList mGroupInfo;

    private ChatInputView mChatView;

    /**
     * 未读消息数量
     */
    private TextView tvUnReadNum;

    /**
     * 昵称
     */
    private TextView tvTitle;

    /**
     * rxbus 注册
     */
    boolean isRegisterEvent = false;

    private final int transparentHeight = (int) (DisplayUtils.getDisplayPxHeight() * 0.36);

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (displayMode > 0 && ev.getY() < transparentHeight) {
                finish();
                return true;
            }
            View view = getCurrentFocus();
            if (isShouldHideInput(view, ev)) {
                KeyboardUtils.hideSoftInput(mActivity);
                return super.dispatchTouchEvent(ev);
            }
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 判断是否为软键盘和输入框外的区域
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            ((View) (v.getParent().getParent().getParent().getParent())).getLocationInWindow(leftTop);
            int top = leftTop[1];
            //点击的是输入框及以下区域，保留点击事件
            return !(event.getY() > top);
        }
        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        super.onCreate(savedInstanceState);
        instance = this;

        if (displayMode == 1) {
            View aa = (View) mNormalLayout.getParent();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewTransparent.getLayoutParams();
            layoutParams.height = transparentHeight;
            aa.setBackgroundResource(R.color.transparent);
            viewTransparent.setLayoutParams(layoutParams);
        } else {
            getWindow().setBackgroundDrawableResource(R.color.white);
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        if (getLifecycle() instanceof LifecycleRegistry) {
            ((LifecycleRegistry) getLifecycle()).markState(Lifecycle.State.CREATED);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        ARouter.getInstance().inject(this);
        mConversationFragment = null;
        installViews();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_conversation;
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.toolbar_back) {
            // 退出
            tryToQuit();
        } else if (i == R.id.iv_setting) {
            // 设置
            if (isGroup) {
                Intent intent = new Intent(this, GroupInfoActivity.class);
                intent.putExtra("extra_id", mHisAccid);
                startActivity(intent);
            } else {
                if (mUserInfo == null) {
                    ToastUtil.showMessage(getString(R.string.get_user_info_fail));
                    return;
                }
                ConversationSettingActivity.startActivity(mActivity, mUserInfo, mHisAccid, false, "");
            }
        }
    }

    @Override
    public void installViews() {

        AndroidBug5497Workaround.assistActivity(this);

        ARouter.getInstance().inject(this);

        if (TextUtils.isEmpty(mHisAccid)) {
            if (getIntent().hasExtra("im_targetId")) {
                hisAccId = getIntent().getStringExtra("im_targetId");

                UserInfo oldUserInfo = RongUserInfoManager.getInstance().getUserInfo(hisAccId);
                if (oldUserInfo != null) {
                    hisNickname = oldUserInfo.getName();
                }
            }
        }

        if (TextUtils.isEmpty(mHisAccid)) {
            mHisAccid = hisAccId;
            mHisNickname = hisNickname;
        }

        if (isGroup) {
            uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversation").appendPath(Conversation.ConversationType.GROUP.getName().toLowerCase())
                    .appendQueryParameter("title", mHisNickname)
                    .appendQueryParameter("targetId", mHisAccid).build();
        } else {
            uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversation").appendPath(Conversation.ConversationType.PRIVATE.getName().toLowerCase())
                    .appendQueryParameter("title", mHisNickname)
                    .appendQueryParameter("targetId", mHisAccid).build();
        }

        ConversationCache.getInstance().setUserId(mHisAccid);

        tvUnReadNum = findViewById(R.id.tvUnReadNum);

        tvTitle = findViewById(R.id.toolbar_title);

        tvTitle.setText(mHisNickname);

        registerForContextMenu(findViewById(R.id.layout_fragment));

        // 返回按钮
        findViewById(R.id.toolbar_back).setOnClickListener(this);

        // 右上角设置入口
        findViewById(R.id.iv_setting).setOnClickListener(this);

        // 添加消息容器
        addMessageFragment();

        // 初始化会话类型
        initConversationType();

        // 获取用户信息
        loadUserData();

        // RX 回调事件
        registerEvent();

        SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.DIALOG_RECHARGE, true);
        ChatInputLoadManager.getInstance().registerChatInputLoadObservable(this);
        RySendImageManager.getInstance().registerSendOpenAgoraObservable(this);
    }

    /**
     * 加载消息容器
     */
    private void addMessageFragment() {
        if (mConversationFragment == null) {
            mConversationFragment = new MessageFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("displayMode", displayMode);
            if (isGroup) {
                mConversationFragment.initConversation(mHisAccid, Conversation.ConversationType.GROUP, bundle);
            } else {
                mConversationFragment.initConversation(mHisAccid, Conversation.ConversationType.PRIVATE, bundle);
            }
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.layout_fragment, mConversationFragment);
            // 提交创建Fragment请求
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 初始化RXBUS
     */
    private void registerEvent() {

        if (isRegisterEvent) {
            return;
        }
        isRegisterEvent = true;

        //融云未读状态更新
        observerRxBus(RongYunMessageUnreadStatusEvent.class, event ->
                showUnReadView(event.getNum())
        );

        // 退出群聊后删除群
        observerRxBus(QuitGroupEvent.class, event -> {
            finish();
        });

        // 获取未读数量
        RongIMClient.getInstance().getUnreadCount(new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                showUnReadView(integer);
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
            }
        }, Conversation.ConversationType.PRIVATE);
    }

    /**
     * 加载未读数
     */
    private void showUnReadView(int num) {

        if (null == tvUnReadNum) {
            return;
        }

        if (0 >= num) {
            tvUnReadNum.setVisibility(View.GONE);
            return;
        }

        tvUnReadNum.setVisibility(View.VISIBLE);
        if (num <= 99) {
            tvUnReadNum.setText(String.valueOf(num));
        } else {
            tvUnReadNum.setText("99+");
        }
    }

    @Override
    public void sendChat(String targetId, String nickName) {

    }

    @Override
    public void sendInputView(ChatInputView inputView) {
        inputView.setRecordVoiceListener(new RecordVoiceListener() {
            @Override
            public void onStartRecord() {
                // 开始录音
                String path = getExternalFilesDir(null).getAbsolutePath() + "/voice";

                File destDir = new File(path);
                if (!destDir.exists()) {
                    destDir.mkdirs();
                }

                inputView.setRecordVoiceFile(destDir.getPath(), DateFormat.format("yyyy-MM-dd-hhmmss", Calendar.getInstance(Locale.CHINA)) + "");
            }

            @Override
            public void onFinishRecord(File file, int duration) {
                // 结束录音
                if (duration < 2) {
                    ToastUtil.showMessage(getString(R.string.talk_short));
                    return;
                }
                HQVoiceMessage hqVoiceMessage = HQVoiceMessage.obtain(Uri.fromFile(file), duration);
                Message message = Message.obtain(mHisAccid, mConversationType, hqVoiceMessage);
                RongIM.getInstance().sendMediaMessage(message, "[语音]", null,
                        new IRongCallback.ISendMediaMessageCallback() {
                            @Override
                            public void onProgress(Message message, int progress) {

                            }

                            @Override
                            public void onCanceled(Message message) {

                            }

                            @Override
                            public void onAttached(Message message) {

                            }

                            @Override
                            public void onSuccess(Message message) {
                            }

                            @Override
                            public void onError(Message message, RongIMClient.ErrorCode errorCode) {

                            }
                        });
            }

            @Override
            public void onCancelRecord() {

            }

            @Override
            public void onPreviewCancel() {

            }

            @Override
            public void onPreviewSend() {

            }
        });

        mChatView = inputView;

        mChatView.setActivity(mActivity);
        mChatView.setMenuContainerHeight(mChatView.getSoftKeyboardHeight());
        mChatView.setRyIm(true);
        menuTouchListener();
    }

    public void initConversationType() {
        String typeStr = Objects.requireNonNull(uri.getLastPathSegment()).toUpperCase(Locale.US);
        mConversationType = Conversation.ConversationType.valueOf(typeStr);
    }

    /**
     * 发送文字消息
     */
    private void sendTextMessage(String msg) {
        mConversationFragment.onSendToggleClick(null, msg, null, () -> {

        });
    }

    /**
     * 关闭键盘
     */
    protected void hideKeyboard() {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.hideSoftInput(this);
        }
    }

    private void menuTouchListener() {

        mChatView.setMenuClickListener(new OnMenuClickListener() {
            @Override
            public boolean onSendTextMessage(CharSequence input, boolean isCheck) {
                if (input != null) {
                    if (input.length() == 0) {
                        return false;
                    }
                    sendTextMessage(input.toString());
                }
                return true;
            }

            @Override
            public void onSendFiles(List<FileItem> list) {
                if (list == null || list.isEmpty()) {
                    return;
                }
                List<String> filePaths = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    filePaths.add(list.get(i).getFilePath());
                }
                showImagesPowerDialog(filePaths);
            }

            @Override
            public boolean openRecordPermission() {
                // 权限校验
                String[] permissions;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                    permissions = new String[]{
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_MEDIA_AUDIO,
                            Manifest.permission.READ_MEDIA_IMAGES,
                            Manifest.permission.READ_MEDIA_VIDEO};
                } else {
                    permissions = new String[]{
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_EXTERNAL_STORAGE};
                }
                PermissionsUtils.getInstance().checkPermission(mActivity, permissions, "Voice", new PermissionsUtils.OnCallBackListener() {
                    @Override
                    public void open(List<String> list) {

                    }

                    @Override
                    public void notOpen(List<String> list, String label) {

                    }
                });
                return true;
            }

            @Override
            public boolean switchToGalleryMode() {
                // 发送图片
                String[] permissions;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                    permissions = new String[]{
                            Manifest.permission.READ_MEDIA_AUDIO,
                            Manifest.permission.READ_MEDIA_IMAGES,
                            Manifest.permission.READ_MEDIA_VIDEO};
                } else {
                    permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
                }
                PermissionsUtils.getInstance().checkPermission(mActivity, permissions, "Album", new PermissionsUtils.OnCallBackListener() {
                    @Override
                    public void open(List<String> list) {
                        mConversationFragment.selectPhoto();
                    }

                    @Override
                    public void notOpen(List<String> list, String label) {

                    }
                });
                return false;
            }

            @Override
            public boolean switchToEmojiMode() {
//                if (CacheEmojiManager.getInstance().getEmojiList().isEmpty()) {
//                    ToastUtil.showMessage(getString(R.string.get_moji_error_check_network));
//                    return false;
//                } else {
                return true;
//                }
            }

            @Override
            public boolean switchToMoreMenu() {
                return true;
            }

            @Override
            public boolean switchToGiftMenu() {
                if (mUserInfo == null) {
                    ToastUtil.showMessage(getString(R.string.get_user_info_error));
                    return false;
                }

                if (!mUserInfo.isFollowed()) {
                    ToastUtil.showMessage("关注对方才能赠送礼物哦～");
                    return true;
                }

                showGiftDialog(null);
                return true;
            }

            @Override
            public boolean switchToVoiceMenu() {
                return true;
            }

            @Override
            public boolean switchToRedPackageMenu() {

                if (mUserInfo != null && !mUserInfo.isFollowed()) {
                    ToastUtil.showMessage("关注对方才能赠送红包哦～");
                    return true;
                }

                Bundle bundle = new Bundle();
                // 红包模块
                if (isGroup) {
                    bundle.putInt("extra_user_count", mGroupInfo.getGroupMemberCount());
                    bundle.putString("extra_game_id", mHisAccid);
                    bundle.putInt("extra_scenario_type", 3);
                    GameRedPkgDialog.showDialog(mActivity, GameRedPkgDialog.class, bundle);
                } else {
                    bundle.putString("extra_user_id", mHisAccid);
                    RedPkgDialog.showDialog(mActivity, RedPkgDialog.class, bundle);
                }
                return false;
            }

            @Override
            public boolean switchTouzi() {
                mConversationFragment.sendChatRoomEmoijShaiZiMessage(DiceUtil.getShaiZiLabel(), DiceUtil.getRandomResult());
                return false;
            }
        });

        mChatView.getSelectAlbumBtn().setOnClickListener(v ->
                mConversationFragment.selectPhoto()
        );

        mChatView.getSelectCameraBtn().setOnClickListener(view ->
                mConversationFragment.selectPhoto()
        );
    }

    /**
     * 钻石礼物弹窗
     */
    private void showGiftDialog(GiftOpenInfo giftOpenInfo) {
        Bundle bundle = new Bundle();
        bundle.putString(IntentConstant.INTENT_USER_ID, mHisAccid);
        bundle.putString(IntentConstant.INTENT_USER_NAME, mHisNickname);
        bundle.putString(IntentConstant.INTENT_SCENARIO, "私聊");
        bundle.putInt("extra_source", 1);
        bundle.putSerializable(IntentConstant.INTENT_GIFT_TITLE, giftOpenInfo);
        BaseDialog.showDialog(mActivity, ChatRoomGiftDialog.class, bundle);
    }

    /**
     * 图片发送
     */
    private void showImagesPowerDialog(List<String> filePaths) {
        sendImagesMsg(filePaths);
    }

    /**
     * 发送图片
     */
    public void sendImagesMsg(List<String> filePaths) {
        for (String filePath : filePaths) {
            MySendImageManager.getInstance().sendImages(mConversationType, mHisAccid, Collections.singletonList(Uri.parse(filePath)),
                    origin, fireStatus, 30, "");
            if (mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                RongIMClient.getInstance().sendTypingStatus(mConversationType, mHisAccid, "RC:ImgMsg");
            }
        }
    }

    boolean origin;

    boolean fireStatus;

    @Override
    public void sendImage(String imagePath, boolean origin, boolean fireStatus) {
        this.origin = origin;
        this.fireStatus = fireStatus;
        List<String> filePaths = new ArrayList<>();
        filePaths.add(imagePath);
        showImagesPowerDialog(filePaths);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (getSupportFragmentManager().getFragments() != null && getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void loadUserData() {
        if (isGroup) {
            List<String> list = new ArrayList<>();
            list.add(mHisAccid);
            BizLayer.getInstance().getAccountModule().loadGroupProfileList(list, new AresSubscriber<GroupProfileBase>() {
                @Override
                protected void onSuccess(GroupProfileBase userProfileList) {
                    if (userProfileList == null || userProfileList.getList() == null || userProfileList.getList().isEmpty()) {
                        return;
                    }
                    mGroupInfo = userProfileList.getList().get(0);
                    setTitle(mGroupInfo.getGroupName() + "(" + mGroupInfo.getGroupMemberCount() + ")");
                    tvTitle.setText(mGroupInfo.getGroupName());
                    try {
                        String groupInfo = JSON.toJSONString(mGroupInfo.getGroupMembers());
                        Group group = new Group(mGroupInfo.getGroupId(), mGroupInfo.getGroupName(), Uri.parse(groupInfo));
                        RongIM.getInstance().setMessageAttachedUserInfo(true);
                        RongIM.getInstance().refreshGroupInfoCache(group);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            BizLayer.getInstance().getAccountModule().getBasicUserInfoRequest(mHisAccid, new AresSubscriber<PersonalDetailBasic>() {
                @Override
                protected void onSuccess(PersonalDetailBasic mBasicUserInfoResponse) {
                    mUserInfo = mBasicUserInfoResponse;
                    tvTitle.setText(mUserInfo.getNickName());
                    String header = mUserInfo.getAvatar() != null ? mUserInfo.getAvatar() : "";
                    UserInfo tempUserInfo = new UserInfo(mHisAccid, mUserInfo.getNickName() != null ? mUserInfo.getNickName() : "", Uri.parse(ImageLoadUtil.url2webp(header, 150)));
                    RongIM.getInstance().setCurrentUserInfo(tempUserInfo);
                    RongIM.getInstance().setMessageAttachedUserInfo(true);
                    RongIM.getInstance().refreshUserInfoCache(tempUserInfo);
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GiftIconEvent event) {
        Log.e("", "IreneBond: giftEvent 1");
        if (mConversationFragment != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.e("", "IreneBond: giftEvent 2");
                    mConversationFragment.notifyDataSetChanged();
                }
            }, 300);
        }
    }

    @Override
    public void onBackPressed() {
        tryToQuit();
    }

    private void tryToQuit() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideKeyboard();
        GiftBatterManager.getInstance().destroyUbi();
        GiftManager.getInstance().setSelectUbiIndex(new int[]{-1, -1, -1, -1});
        GiftManager.getInstance().setTabId(null);
        ChatInputLoadManager.getInstance().unRegisterChatInputLoadObservable(this);
        RySendImageManager.getInstance().unRegisterSendOpenAgoraObservable(this);
        instance = null;
        KeyboardUtils.unregisterSoftInputChangedListener(this);
    }
}